// 初始化日志
console.log('AI提醒助手后台脚本已加载');

// 初始化存储设置
chrome.runtime.onInstalled.addListener(() => {
  console.log('扩展已安装，初始化设置');
  chrome.storage.sync.set({
    reminderStrength: 'medium' // 默认为中等提醒强度
  });
});

// 记录上次提醒时间
let lastReminderTime = {
  medium: 0, // 每小时最多提示一次
  weak: 0    // 每天最多提示一次
};

// 监听标签页更新事件
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
  // 只有当页面完全加载时才检查
  if (changeInfo.status === 'complete' && tab.url) {
    console.log('页面加载完成:', tab.url);
    
    try {
      const url = new URL(tab.url);
      const isSearchEngine = checkIfSearchEngine(url);
      
      if (isSearchEngine) {
        console.log('检测到搜索页面:', url.toString());
        
        chrome.storage.sync.get('reminderStrength', (data) => {
          const { reminderStrength } = data;
          console.log('当前提醒强度:', reminderStrength);
          
          if (shouldShowReminder(reminderStrength)) {
            console.log('应该显示提醒，准备执行脚本');
            // 更新最后提醒时间
            updateLastReminderTime(reminderStrength);
            
            // 使用executeScript直接在页面中执行脚本
            chrome.scripting.executeScript({
              target: { tabId: tabId },
              function: showReminderDirectly
            })
            .then(() => console.log('提醒脚本已执行'))
            .catch(err => console.error('执行脚本失败:', err));
          } else {
            console.log('根据设置不显示提醒');
          }
        });
      }
    } catch (error) {
      console.error('URL处理出错:', error);
    }
  }
});

// 判断是否是搜索引擎搜索页面
function checkIfSearchEngine(url) {
  const hostname = url.hostname;
  const pathname = url.pathname;
  const searchParams = url.searchParams;
  
  // Google搜索
  if (hostname.includes('google.com') && pathname.includes('/search') && searchParams.has('q')) {
    return true;
  }
  
  // Bing搜索
  if (hostname.includes('bing.com') && pathname.includes('/search') && searchParams.has('q')) {
    return true;
  }
  
  // Baidu搜索
  if (hostname.includes('baidu.com') && pathname.includes('/s') && searchParams.has('wd')) {
    return true;
  }
  
  // Yahoo搜索
  if (hostname.includes('yahoo.com') && pathname.includes('/search') && searchParams.has('p')) {
    return true;
  }
  
  // DuckDuckGo搜索
  if (hostname.includes('duckduckgo.com') && searchParams.has('q')) {
    return true;
  }
  
  // Yandex搜索
  if (hostname.includes('yandex.com') && pathname.includes('/search') && searchParams.has('text')) {
    return true;
  }
  
  // 搜狗搜索
  if (hostname.includes('sogou.com') && pathname.includes('/web') && searchParams.has('query')) {
    return true;
  }
  
  return false;
}

// 判断是否应该显示提醒
function shouldShowReminder(strength) {
  const now = Date.now();
  
  switch (strength) {
    case 'strong':
      // 每次搜索都提醒
      return true;
    
    case 'medium':
      // 每小时最多提醒一次
      if (now - lastReminderTime.medium > 60 * 60 * 1000) {
        return true;
      }
      return false;
    
    case 'weak':
      // 每天最多提醒一次
      if (now - lastReminderTime.weak > 24 * 60 * 60 * 1000) {
        return true;
      }
      return false;
    
    default:
      return true;
  }
}

// 更新最后提醒时间
function updateLastReminderTime(strength) {
  const now = Date.now();
  
  if (strength === 'medium') {
    lastReminderTime.medium = now;
  } else if (strength === 'weak') {
    lastReminderTime.weak = now;
  }
}

// 直接在页面中显示提醒的函数（会被注入到页面中执行）
function showReminderDirectly() {
  console.log('页面中直接执行显示提醒');
  
  // 添加样式
  const style = document.createElement('style');
  style.textContent = `
    #ai-reminder-popup {
      position: fixed;
      top: 20px;
      right: 20px;
      z-index: 999999;
      max-width: 300px;
      opacity: 0;
      transform: translateY(-20px);
      transition: opacity 0.3s ease, transform 0.3s ease;
    }
    
    #ai-reminder-popup.show {
      opacity: 1;
      transform: translateY(0);
    }
    
    #ai-reminder-popup.hide {
      opacity: 0;
      transform: translateY(-20px);
    }
    
    .ai-reminder-content {
      background-color: #fff;
      border-radius: 12px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      padding: 16px;
      display: flex;
      align-items: center;
      border: 1px solid #e1e4e8;
      animation: pulse 2s infinite;
    }
    
    @keyframes pulse {
      0% {
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      }
      50% {
        box-shadow: 0 4px 20px rgba(77, 156, 255, 0.3);
      }
      100% {
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      }
    }
    
    .ai-reminder-icon {
      background-color: #4d9cff;
      color: white;
      width: 36px;
      height: 36px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 12px;
      flex-shrink: 0;
    }
    
    .ai-reminder-message {
      flex-grow: 1;
      font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
    }
    
    .ai-reminder-message p {
      margin: 0;
      font-size: 14px;
      color: #24292e;
      font-weight: 500;
    }
    
    .ai-reminder-close {
      width: 20px;
      height: 20px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      font-size: 18px;
      color: #6e7781;
      margin-left: 8px;
    }
    
    .ai-reminder-close:hover {
      color: #24292e;
    }
  `;
  document.head.appendChild(style);
  
  // 创建提醒元素
  const reminderElement = document.createElement('div');
  reminderElement.id = 'ai-reminder-popup';
  reminderElement.innerHTML = `
    <div class="ai-reminder-content">
      <div class="ai-reminder-icon">
        <svg viewBox="0 0 24 24" width="24" height="24">
          <path fill="currentColor" d="M12,2A10,10 0 0,1 22,12A10,10 0 0,1 12,22A10,10 0 0,1 2,12A10,10 0 0,1 12,2M12,4A8,8 0 0,0 4,12A8,8 0 0,0 12,20A8,8 0 0,0 20,12A8,8 0 0,0 12,4M12,10.5A1.5,1.5 0 0,1 13.5,12A1.5,1.5 0 0,1 12,13.5A1.5,1.5 0 0,1 10.5,12A1.5,1.5 0 0,1 12,10.5M7.5,9.5C8.33,9.5 9,8.83 9,8C9,7.17 8.33,6.5 7.5,6.5C6.67,6.5 6,7.17 6,8C6,8.83 6.67,9.5 7.5,9.5M16.5,9.5C17.33,9.5 18,8.83 18,8C18,7.17 17.33,6.5 16.5,6.5C15.67,6.5 15,7.17 15,8C15,8.83 15.67,9.5 16.5,9.5M12,14.5C13.68,14.5 15.12,15.5 15.68,17H8.32C8.88,15.5 10.32,14.5 12,14.5Z"></path>
        </svg>
      </div>
      <div class="ai-reminder-message">
        <p>先等等，这件事可以用AI吗？</p>
      </div>
      <div class="ai-reminder-close">×</div>
    </div>
  `;
  
  // 添加到页面
  document.body.appendChild(reminderElement);
  
  // 显示动画
  setTimeout(() => {
    reminderElement.classList.add('show');
  }, 100);
  
  // 点击关闭按钮
  const closeButton = reminderElement.querySelector('.ai-reminder-close');
  closeButton.addEventListener('click', () => {
    hideReminderElement(reminderElement);
  });
  
  // 5秒后自动关闭
  setTimeout(() => {
    hideReminderElement(reminderElement);
  }, 5000);
  
  // 隐藏提醒
  function hideReminderElement(element) {
    element.classList.remove('show');
    element.classList.add('hide');
    
    // 动画结束后移除元素
    setTimeout(() => {
      if (element.parentNode) {
        element.parentNode.removeChild(element);
      }
    }, 500);
  }
} 